package com.symbio.ishenapi.order.controller;


import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.symbio.ishenapi.common.controller.BaseController;
import com.symbio.ishenapi.order.aliay.AlipayConfig;
import com.symbio.ishenapi.order.aliay.AlipayNotify;

import com.symbio.ishenapi.order.model.TmServiceOrder;
import io.jboot.web.controller.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import static com.symbio.ishenapi.order.aliay.AlipayConfig.ALIPAY_PUBLIC_KEY;


@RequestMapping("/alipay")
public class AliPayController extends BaseController {


public void get() throws Exception{
    AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do","app_id","your private_key","json","GBK","alipay_public_key");
    AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
    request.setBizContent("{" +
            "\"out_trade_no\":\"20150320010101001\"," +
            "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
            "\"total_amount\":88.88," +
            "\"subject\":\"Iphone6 16G\"," +
            "\"body\":\"Iphone6 16G\"," +
            "\"time_expire\":\"2016-12-31 10:05\"," +
            "      \"goods_detail\":[{" +
            "        \"goods_id\":\"apple-01\"," +
            "\"alipay_goods_id\":\"20010001\"," +
            "\"goods_name\":\"ipad\"," +
            "\"quantity\":1," +
            "\"price\":2000," +
            "\"goods_category\":\"34543238\"," +
            "\"body\":\"特价手机\"," +
            "\"show_url\":\"http://www.alipay.com/xxx.jpg\"" +
            "        }]," +
            "\"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\"," +
            "\"extend_params\":{" +
            "\"sys_service_provider_id\":\"2088511833207846\"," +
            "\"hb_fq_num\":\"3\"," +
            "\"hb_fq_seller_percent\":\"100\"," +
            "\"industry_reflux_info\":\"{\\\\\\\"scene_code\\\\\\\":\\\\\\\"metro_tradeorder\\\\\\\",\\\\\\\"channel\\\\\\\":\\\\\\\"xxxx\\\\\\\",\\\\\\\"scene_data\\\\\\\":{\\\\\\\"asset_name\\\\\\\":\\\\\\\"ALIPAY\\\\\\\"}}\"," +
            "\"card_type\":\"S0JP0000\"" +
            "    }," +
            "\"goods_type\":\"0\"," +
            "\"timeout_express\":\"90m\"," +
            "\"promo_params\":\"{\\\"storeIdType\\\":\\\"1\\\"}\"," +
            "\"royalty_info\":{" +
            "\"royalty_type\":\"ROYALTY\"," +
            "        \"royalty_detail_infos\":[{" +
            "          \"serial_no\":1," +
            "\"trans_in_type\":\"userId\"," +
            "\"batch_no\":\"123\"," +
            "\"out_relation_id\":\"20131124001\"," +
            "\"trans_out_type\":\"userId\"," +
            "\"trans_out\":\"2088101126765726\"," +
            "\"trans_in\":\"2088101126708402\"," +
            "\"amount\":0.1," +
            "\"desc\":\"分账测试1\"," +
            "\"amount_percentage\":\"100\"" +
            "          }]" +
            "    }," +
            "\"sub_merchant\":{" +
            "\"merchant_id\":\"19023454\"," +
            "\"merchant_type\":\"alipay: 支付宝分配的间连商户编号, merchant: 商户端的间连商户编号\"" +
            "    }," +
            "\"enable_pay_channels\":\"pcredit,moneyFund,debitCardExpress\"," +
            "\"store_id\":\"NJ_001\"," +
            "\"disable_pay_channels\":\"pcredit,moneyFund,debitCardExpress\"," +
            "\"qr_pay_mode\":\"1\"," +
            "\"qrcode_width\":100," +
            "\"settle_info\":{" +
            "        \"settle_detail_infos\":[{" +
            "          \"trans_in_type\":\"cardSerialNo\"," +
            "\"trans_in\":\"A0001\"," +
            "\"summary_dimension\":\"A0001\"," +
            "\"settle_entity_id\":\"2088xxxxx;ST_0001\"," +
            "\"settle_entity_type\":\"SecondMerchant、Store\"," +
            "\"amount\":0.1" +
            "          }]" +
            "    }," +
            "\"invoice_info\":{" +
            "\"key_info\":{" +
            "\"is_support_invoice\":true," +
            "\"invoice_merchant_name\":\"ABC|003\"," +
            "\"tax_num\":\"1464888883494\"" +
            "      }," +
            "\"details\":\"[{\\\"code\\\":\\\"100294400\\\",\\\"name\\\":\\\"服饰\\\",\\\"num\\\":\\\"2\\\",\\\"sumPrice\\\":\\\"200.00\\\",\\\"taxRate\\\":\\\"6%\\\"}]\"" +
            "    }," +
            "\"agreement_sign_params\":{" +
            "\"personal_product_code\":\"GENERAL_WITHHOLDING_P\"," +
            "\"sign_scene\":\"INDUSTRY|CARRENTAL\"," +
            "\"external_agreement_no\":\"test\"," +
            "\"external_logon_id\":\"13852852877\"," +
            "\"sign_validity_period\":\"2m\"," +
            "\"third_party_type\":\"PARTNER\"," +
            "\"buckle_app_id\":\"1001164\"," +
            "\"buckle_merchant_id\":\"268820000000414397785\"," +
            "\"promo_params\":\"{\\\"key\\\",\\\"value\\\"}\"" +
            "    }," +
            "\"integration_type\":\"PCWEB\"," +
            "\"request_from_url\":\"https://\"," +
            "\"business_params\":\"{\\\"data\\\":\\\"123\\\"}\"," +
            "\"ext_user_info\":{" +
            "\"name\":\"李明\"," +
            "\"mobile\":\"16587658765\"," +
            "\"cert_type\":\"IDENTITY_CARD\"," +
            "\"cert_no\":\"362334768769238881\"," +
            "\"min_age\":\"18\"," +
            "\"fix_buyer\":\"F\"," +
            "\"need_check_info\":\"F\"" +
            "    }" +
            "  }");
    AlipayTradePagePayResponse response = alipayClient.execute(request);

    if(response.isSuccess()){
        System.out.println("调用成功");
    } else {
        System.out.println("调用失败");
    }
}


    /**
     * 拼串
     *
     */
    public void creaSig(){
        String orderId = getPara("id");
    /*public static void main(String[] args) {*/
       String privateKey="MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC6XT8gLfre0zB1XOM55WQfhWdV+X2gijLt1WNteq/5X9A+8jPY07WGbdmW0euCRVoUEGbwqxpXtr5TcQZj5nSs3by8KMzjzrOBnSLCidBokt3lr/rARMZUmLIFPKDloGl7G4qyNfEXiZ1VQfkiofRuXuAsLLug9IKsojChjFN+WjDhWaGvLGxU0Z4t8rbjcq/ZlOXBdHb8nurBD+0+UCqg0dS8M7Xq/gsdwS/+mnG56R41kgAcyFWLlg2qFlc/RYy0SygEX5KTdMWqPXdS9RFEgRoDuYHLZMIBZK5+meL9xKPJ/w9ILStTqkrQtZEVG+Rd3s5WLmXvFnt+3K8ijoddAgMBAAECggEBAKYKajGrhbZ9htEp/zEYFcqXuue4r5sXRiTsV/e0tZCDMzDB7jui9DpfKNvdD+0zCPyTWIPYjlHT+WKycrUTIKTbskoaN+JHyVsTu2KEEvD42UbJMamYHPRGT2WnDNtJvnD2qu34bWNBMrJBY0zd6r9jPGtfN5RCBSL2JknokoMhJs1d/Ts4Ch8k1lud/oF1VQk7R+0g26OS337uqK69fC+6haHBxYds22W6+NW8nPeGrrJep9YjRa1+llPE0bLRtMZ6mSRBAzH+2H8Wy2fa7Hp8AGvXHLzttBWpu921AyvDnaKteY692MLY0LKWnqMnrktn8QHqOEDnQzSyse+hoSkCgYEA4FDA/NG3C9iiyIPuB86E6JadqEA5cRemg0oAnOnJOdoJ/gnaTnyXJlGXqD/LWxY65So702CPvCIwgPKLh9GhK/W+FZEiRwoNoOv966ONMuLkaX/9LovJ4UspOkiPNKtsUB8YlV0Iola+JdR+W+CgYR7b06p3AYONPpN6QJrrUx8CgYEA1LAtaO0dGyV5fi11XDY91XAfcHdcx2PHqdgr8e4HqO4I3p0PxuqU3TFKBjiL0jwW7ZFwI0L7MYJH51tPDe7BAl3n8Wf/VGE+D3QGYXzaaWkScrtHNXqSclpLRA5nWAszpDt/srrAVFaOo0qFwHXlH9lY3/QR1wMl0Z40GHbfsgMCgYAtNtnPnA4Da0VUmZMvK6eKomFg+qEZdKTxrcb12gHfkV2WQTIpw99LsAKbvVAmKhLxAlRQxRPz3ghc1Ybed5i/HaeU/U4ld5dLqoXiK3NYoHdd9Jh5+19T9Cx5PQrwmOUaOUphQQFuh4GIao6Vwm9RZED3J1MZkQS1alCoGRH6DQKBgDpFBjvf8oB0dOOnyqZ3ydsG++YRHZ8W7CXRLsD6aKjUhiOPPjpOHHi5P0GTDmOLyPBPTzyp5i37Nn3hGziC9+gRGDGgP2i7t4f+Tp042pHUkpRSUMELEsI3kLVViOSrNPvCvUqXNYglqrB8A0bmRd7C6kF5GcYhe6QBRt6I+uJHAoGBAJ9fC12Nut+FTsrDwq0cx8A7lMHPbDZJUd/6rP9vvyvXvpeUIaQBSnimOWWMAjT5OvGROH9IgRl4V8CZmnq8XBMUdPBVgk0maploLHZyZY8PdSR9QUQGCt08yL8g2jYN2wlQMOM/Fuj8TSoF0PYX5PtJorO994EIDZKDOp+PNaFv";
       String publickey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkcYy+w9zzkGWzJMKD77uYJPg2u0Gz61qBqshM11ZXZGelmwxkPqos1DZSb7QAJrrAgw1DjyWrDoKSbmB+UApetELwaUlmm4JDjIlbwl2OwPXySfpH942Gp2nO/Rx54D5Rowl5hLMTWLqOuPvKW1ywjpz6SMOuA4Z67eExww/LzU0Y26ja64VcU59Y56xUlGuB6yXcy2hs4TS4hthIlJATQYF9QXxH6SkK89Eihf8CYrtn0XnaHLZHloxBLY1hBZT2ojzuOJQR2yiBlyluha/K72H/bdzQy6lzvAivbH/apFGlcyx3fTClAkO/unD8zu7KnQvLzLVplAtUJ69gbT7rQIDAQAB";

        TmServiceOrder order = TmServiceOrder.dao.getById(new BigInteger(orderId));//根据订单id查询数据
       //实例化客户端
       AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", "2017120900488760",
                privateKey, AlipayConfig.FORMAT, AlipayConfig.CHARSET,
                publickey,AlipayConfig.SIGNTYPE);
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody("我是测试数据");
        model.setSubject("App支付测试Java");
        model.setOutTradeNo(order.getId().toString());
        model.setTimeoutExpress("30m");
        model.setTotalAmount(order.getOrderPrice().toString());
        model.setProductCode("QUICK_MSECURITY_PAY");
        request.setBizModel(model);
       // request.setNotifyUrl("商户外网可以访问的异步地址");
       try {
            System.out.println("--------------------"+request);
            //这里和普通的接口调用不同，使用的是sdkExecute
            String b = alipayClient.sdkExecute(request).getBody();//就是orderString 可以直接给客户端请求，无需再做处理。
            System.out.println("======================"+b);
           renderJsonRet(b);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
    }







    /**
     * 支付宝支付订单
     * @return
     * @throws IOException
     */
    public void aliPayOrder() throws IOException {
        //LOGGER.info("支付订单");
        HttpServletRequest request = getRequest();
        HttpServletResponse response = getResponse();
        //从request中获得参数Map，并返回可读的Map
        Map<String, String> params = getParameterMap(request);
       // LOGGER.info(params.toString());
        //验证支付宝签名
        boolean aliSign = AlipayNotify.verify(params);
        if (aliSign) {//验证成功
            //交易状态
            String tradeStatus = params.get("trade_status");
            //订单编号
            String orderNo = params.get("out_trade_no");
            //支付单号
            String payNo = params.get("trade_no");
            //支付账号
            //String payAccount = params.get("buyer_email");
            //支付金额
           // String totalFee = params.get("total_fee");
            //收款支付宝账号
            //String sellerId = params.get("seller_id");
            TmServiceOrder serviceOrder = new TmServiceOrder();
            serviceOrder.setId(new BigInteger(orderNo));
            TmServiceOrder tmServiceOrderList = TmServiceOrder.dao.findOne(serviceOrder);
            String orderHandleStatus = "";
            if ("ALIPAY_TRADE_SUCCESS".equals(tradeStatus)) {//支付宝支付状态为成功
                if(tmServiceOrderList == null ){
                    response.getWriter().print("fail");
                    return;
                }
                try {
                    //支付成功处理支付业务
                    int result = TmServiceOrder.dao.updateOrderStatus(tmServiceOrderList.getId(),"18918005","支付宝");
                    if (result == 1) {
                        //成功后向支付宝返回成功标志
                       // LOGGER.info("支付宝支付成功");
                        orderHandleStatus = "success";
                        response.getWriter().print("success");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    //LOGGER.info("支付宝支付失败");
                    response.getWriter().print("fail");
                }
                //验证支付宝返回信息与请求信息一致
               // if (ProInfoUtil.getInstance().getProperty("alipay_partner").equals(sellerId)) {
                    //订单处理状态
                    orderHandleStatus = "error";
                    //验证订单未做支付处理
                   // Order order = orderService.queryOrderByOrderNo(orderNo);
                    //订单已支付
                   /* if ("DEALSTATUS_PAY".equals(order.getDealStatus())) {
                        response.getWriter().print("success");
                        return;
                    }*/
                  /*  if (null != order && Double.parseDouble(totalFee) == order.getDealPrice() &&
                            Constant.DEALSTATUS_NOT_PAY.equals(order.getDealStatus())) {//验证金额是否和订单一致
                        //更新订单为已支付、更新用户套餐余额、添加用户充值记录、添加用户余额支出记录
                        order.setDealStatus(Constant.DEALSTATUS_PAY);
                        order.setPayNo(payNo);
                        order.setPayType(Constant.ALIPAY);
                        order.setPayAccount(payAccount);
                        try {
                            //支付成功处理支付业务
                            boolean result = orderService.payOrder(order);
                            if (result) {
                                //成功后向支付宝返回成功标志
                                LOGGER.info("支付宝支付成功");
                                orderHandleStatus = "success";
                                response.getWriter().print("success");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            LOGGER.info("支付宝支付失败");
                            response.getWriter().print("fail");
                        }

                    }*/
                    //添加支付信息
                    Map<String, Object> map = new HashMap<String, Object>();
                   /* map.put("params", params.toString());
                    map.put("payType", Constant.ALIPAY);
                    map.put("orderNo", orderNo);*/
                    map.put("handleStatus", orderHandleStatus);
                    //orderService.addPayInfo(map);
               // }
            }else{
                int result = TmServiceOrder.dao.updateOrderStatus(tmServiceOrderList.getId(),"18918005","支付宝");
                response.getWriter().print("fail");
            }

       } else {//验证失败
            //LOGGER.info("支付宝返回验证失败");
            response.getWriter().print("fail");
        }
    }


    /**
     * 从request中获得参数Map，并返回可读的Map
     *
     * @param request
     * @return
     */
    @SuppressWarnings("unchecked")
    public Map getParameterMap(HttpServletRequest request) {
        // 参数Map
        Map properties = request.getParameterMap();
        // 返回值Map
        Map<String, String> returnMap = new HashMap<String, String>();
        Iterator entries = properties.entrySet().iterator();
        Map.Entry entry;
        String name = "";
        String value = "";
        while (entries.hasNext()) {
            entry = (Map.Entry) entries.next();
            name = (String) entry.getKey();
            Object valueObj = entry.getValue();
            if(null == valueObj){
                value = "";
            }else if(valueObj instanceof String[]){
                String[] values = (String[])valueObj;
                for(int i=0;i<values.length;i++){
                    value = values[i] + ",";
                }
                value = value.substring(0, value.length()-1);
            }else{
                value = valueObj.toString();
            }
            returnMap.put(name, value);
        }
        return returnMap;

    }
}
